package com.lxl.xm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.lxl.xm.common.BaseResponse;
import com.lxl.xm.common.ErrorCode;
import com.lxl.xm.common.ResultUtils;
import com.lxl.xm.exception.BusinessException;
import com.lxl.xm.model.dto.face.FaceSearchResDto;
import com.lxl.xm.model.dto.face.ProcessInfo;
import com.lxl.xm.model.dto.student.FaceStudentInfo;
import com.lxl.xm.service.FaceEngineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 人脸识别
 */
@RestController
@RequestMapping("/face")
@Slf4j
public class FaceController {

    @Resource
    FaceEngineService faceEngineService;



    /**
     * 图片使用base64编码传递到后端
     * 人脸信息比对
     * @param file
     * @return
     */
    @PostMapping("/faceSearch")
    public BaseResponse<Boolean> faceSearch(@RequestParam("file") String file, Integer groupId) throws Exception {
        if (file == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件上传信息错误");
        }
        byte[] decode = Base64.decode(base64Process(file));
        BufferedImage bufImage = null;
        try {
            bufImage = ImageIO.read(new ByteArrayInputStream(decode));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ImageInfo imageInfo = ImageFactory.bufferedImage2ImageInfo(bufImage);

        //人脸特征获取
        byte[] bytes = faceEngineService.extractFaceFeature(imageInfo);
        if (bytes == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"无人脸特征");
        }
        //人脸比对，获取比对结果
        List<FaceStudentInfo> userFaceInfoList = faceEngineService.compareFaceFeature(bytes, groupId);

        if (CollectionUtil.isNotEmpty(userFaceInfoList)) {
            FaceStudentInfo faceUserInfo = userFaceInfoList.get(0);
            FaceSearchResDto faceSearchResDto = new FaceSearchResDto();
            BeanUtil.copyProperties(faceUserInfo, faceSearchResDto);
            List<ProcessInfo> processInfoList = faceEngineService.process(imageInfo);
            if (CollectionUtil.isNotEmpty(processInfoList)) {
                //人脸检测
                List<FaceInfo> faceInfoList = faceEngineService.detectFaces(imageInfo);
                int left = faceInfoList.get(0).getRect().getLeft();
                int top = faceInfoList.get(0).getRect().getTop();
                int width = faceInfoList.get(0).getRect().getRight() - left;
                int height = faceInfoList.get(0).getRect().getBottom() - top;

                Graphics2D graphics2D = bufImage.createGraphics();
                graphics2D.setColor(Color.RED);//红色
                BasicStroke stroke = new BasicStroke(5f);
                graphics2D.setStroke(stroke);
                graphics2D.drawRect(left, top, width, height);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(bufImage, "jpg", outputStream);
                byte[] bytes1 = outputStream.toByteArray();
//                faceSearchResDto.setImage("data:image/jpeg;base64," + Base64Utils.encodeToString(bytes1));
                faceSearchResDto.setAge(processInfoList.get(0).getAge());
                faceSearchResDto.setGender(processInfoList.get(0).getGender().equals(1) ? "女" : "男");
            }
            log.info("人脸比对信息：{}",faceSearchResDto.toString());
            //相似度对比
            return ResultUtils.success(faceSearchResDto.getSimilarValue() > 80);
        }
        return ResultUtils.success(false);

    }




    private String base64Process(String base64Str) {
        if (!StringUtils.isEmpty(base64Str)) {
            String photoBase64 = base64Str.substring(0, 30).toLowerCase();
            int indexOf = photoBase64.indexOf("base64,");
            if (indexOf > 0) {
                base64Str = base64Str.substring(indexOf + 7);
            }

            return base64Str;
        } else {
            return "";
        }
    }

}
